const koaRouter = require('koa-router')
const router = new koaRouter()


const login = require('../middleware/user/login')
const logout = require('../middleware/user/logout')
const online = require('../middleware/user/online')
const getinfo = require('../middleware/user/getinfo')
const error = require('../middleware/common/error')
const modify = require('../middleware/user/modify')
const admin = require('../middleware/user/admin')
const list = require('../middleware/user/list')
const register = require('../middleware/user/register')
const { Success } = require('../lib/Response')

router.prefix('/users')

/**
 * 获取信息
 */
router.get(['/info', '/'], online, getinfo)

/** 登录 */
router.post(['/login', '/'], async function (ctx, next) {
  ctx.checkBody('name').len(2, 20);
  ctx.checkBody('pwd').len(2, 20).md5();
  await next();
}, error, login)

/** 修改 */
router.put(['/', '/info'], online, async function (ctx, next) {
  ctx.checkBody('sex').optional().isIn(['男', '女']).default(ctx.session.user.sex);
  ctx.checkBody('pwd').optional().len(6, 20).md5().default(ctx.session.user.pwd);
  await next();
}, error, modify, async function (ctx, next) {
  if (ctx.request.body.pwd !== ctx.session.user.pwd) {
    await next();
  }
}, logout)

/** 登出 */
router.get(['/logout', '/exit'], online, logout, async function (ctx, next) {
  ctx.body = new Success()
})


/** 列表 */
router.get(['/list'], online, admin, async function (ctx, next) {
  console.log(ctx.request.query)
  ctx.checkQuery('limit').optional().isInt('limit 参数不正确').toInt().default(10);
  ctx.checkQuery('offset').optional().isInt('offset 参数不正确').toInt().default(0);
  console.log(ctx.request.query)
  await next();
}, error, list)

/** 注册（患者）[目前没有什么用] */
router.post(['/register'], async function (ctx, next) {
  ctx.checkBody('name').empty();
  ctx.checkBody('pwd').empty().md5();
  ctx.checkBody('sex').optional().isIn(['男', '女']).default('男');
  await next()
}, register)

// 注册

module.exports = router
